
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:jverify/jverify.dart';
import '../../../common/colors.dart';
import '../../../services/address.dart';
import '../../../utils/hexcolor.dart';
import '../../../utils/load.dart';
import '../../../utils/persisten_storage.dart';
import '../../bottom_tab_controller.dart';
import 'dart:async';
import 'dart:io';

import 'package:app/services/dio_manager.dart';
import '../login_face.dart';
import '../../login_modules/login_view.dart';
import '../../login_modules/login_model.dart';

import 'package:bot_toast/bot_toast.dart';


class OauthPage extends StatefulWidget {
  const OauthPage({Key? key}) : super(key: key);

  @override
  State<OauthPage> createState() => _OauthPageState();
}

class _OauthPageState extends State<OauthPage> {
  //授权页登录业务逻辑添加
  var loginacctoken = "";

  void getInitData() async {
    print("loginacctoken==print>>");
    loginacctoken = await PersistentStorage().getStorage('acctoken');
    print("loginacctoken===print>>" + loginacctoken);
    setState(() {
      print("loginacctoken==async>>" + loginacctoken);
    });
    if (loginacctoken.length > 0) {
      Get.offAll(Tabs());
    }
  }

  @override
  void initState() {
    super.initState();
    initPlatformState();
    getInitData();
    print("loginacctoken==>>>" + loginacctoken);
  }

  final Jverify jverify = Jverify();

  /// 统一 key
  final String f_result_key = "result";

  /// 错误码
  final String f_code_key = "code";

  /// 回调的提示信息，统一返回 flutter 为 message
  final String f_msg_key = "message";

  /// 运营商信息
  final String f_opr_key = "operator";

  String _result = "token=";

  /// SDK 请求授权一键登录
  void _showLoading(BuildContext context) {
    LoadingDialog.show(context);
  }

  void _hideLoading() {
    LoadingDialog.hidden();
  }

  requestDataWithToken(var loginToken) async {
    var params = {
      'login_token': loginToken,
      'client_type': 'app',
    };

    var json = await DioManager()
        .kkRequest(Address.oauth, bodyParams: params, isShowLoad: true);


    print('一键登录==================${json}');

    Usesr model = Usesr.fromJson(json);

    if (model.errmsg == 'ok') {
      // await prefs.setString('acctoken', _model.data.accessToken);
      PersistentStorage().setStorage('acctoken', model.data!.accessToken);
      PersistentStorage().setStorage('uid', model.data!.uid);
      PersistentStorage().setStorage('partner_id', model.data!.partnerId);
      PersistentStorage().setStorage('image128', model.data!.image128);
      PersistentStorage()
          .setStorage('job_company_id', model.data!.jobCompanyId.toString());
      PersistentStorage()
          .setStorage('job_user_id', model.data!.jobUserId.toString());
      PersistentStorage().setStorage('name', model.data!.name);
      PersistentStorage().setStorage('login_mobile', model.data!.login_mobile);
      PersistentStorage()
          .setStorage('companyIdName', model.data!.companyIdName);
      PersistentStorage()
          .setStorage('companyId', model.data!.companyId.toString());
      PersistentStorage()
          .setStorage('company_ids_name', model.data!.companyIdsName);

      Get.offAll(Tabs());

      // Get.to(HomePage());

    } else {
      BotToast.showText(text: json['message']);
    }
  }

  /// SDK 请求授权一键登录
  void loginAuth() {
    setState(() {
      _showLoading(context);
    });
    jverify.checkVerifyEnable().then((map) {
      bool result = map[f_result_key];
      if (result) {
        final screenSize = MediaQuery.of(context).size;
        final screenWidth = screenSize.width;
        final screenHeight = screenSize.height;
        bool isiOS = Platform.isIOS;

        /// 自定义授权的 UI 界面，以下设置的图片必须添加到资源文件里，
        /// android项目将图片存放至drawable文件夹下，可使用图片选择器的文件名,例如：btn_login.xml,入参为"btn_login"。
        /// ios项目存放在 Assets.xcassets。
        ///
        JVUIConfig uiConfig = JVUIConfig();
        // uiConfig.authBGGifPath = "main_gif";

        //uiConfig.navHidden = true;
        uiConfig.navColor = Colors.white.value;

        uiConfig.navTextColor = Colors.black.value;
        uiConfig.navReturnImgPath = "leftarr"; //图片必须存在

        uiConfig.logoWidth = 100;
        uiConfig.logoHeight = 100;
        //uiConfig.logoOffsetX = isiOS ? 0 : null;//(screenWidth/2 - uiConfig.logoWidth/2).toInt();
        uiConfig.logoOffsetY = 10;
        uiConfig.logoVerticalLayoutItem = JVIOSLayoutItem.ItemSuper;
        uiConfig.logoHidden = false;
        uiConfig.logoImgPath = "log_icon";

        uiConfig.numberFieldWidth = 200;
        uiConfig.numberFieldHeight = 40;
        //uiConfig.numFieldOffsetX = isiOS ? 0 : null;//(screenWidth/2 - uiConfig.numberFieldWidth/2).toInt();
        uiConfig.numFieldOffsetY = isiOS ? 20 : 120;
        uiConfig.numberVerticalLayoutItem = JVIOSLayoutItem.ItemLogo;
        uiConfig.numberColor = AppColor.themeColor.value;
        uiConfig.numberSize = 18;

        uiConfig.sloganOffsetY = isiOS ? 20 : 160;
        uiConfig.sloganVerticalLayoutItem = JVIOSLayoutItem.ItemNumber;
        uiConfig.sloganTextColor = Colors.black.value;
        uiConfig.sloganTextSize = 15;
//        uiConfig.slogan
        //uiConfig.sloganHidden = 0;

        uiConfig.logBtnWidth = 220;
        uiConfig.logBtnHeight = 50;
        uiConfig.logBtnBackgroundPath = 'btn_background';
        //uiConfig.logBtnOffsetX = isiOS ? 0 : null;//(screenWidth/2 - uiConfig.logBtnWidth/2).toInt();
        uiConfig.logBtnOffsetY = isiOS ? 20 : 230;
        uiConfig.logBtnVerticalLayoutItem = JVIOSLayoutItem.ItemSlogan;
        uiConfig.logBtnText = "登录";
        uiConfig.logBtnTextColor = Colors.white.value;
        uiConfig.logBtnTextSize = 16;

        uiConfig.loginBtnNormalImage = "login_btn_normal"; //图片必须存在
        uiConfig.loginBtnPressedImage = "login_btn_press"; //图片必须存在
        uiConfig.loginBtnUnableImage = "login_btn_unable"; //图片必须存在

        uiConfig.privacyHintToast =
            true; //only android 设置隐私条款不选中时点击登录按钮默认显示toast。

        uiConfig.privacyState = true; //设置默认勾选
        uiConfig.privacyCheckboxSize = 20;
        uiConfig.checkedImgPath = "check_image"; //图片必须存在
        uiConfig.uncheckedImgPath = "uncheck_image.png"; //图片必须存在
        uiConfig.privacyCheckboxInCenter = true;
        uiConfig.privacyNavTitleTextColor = AppColor.themeColor.value;
        //uiConfig.privacyCheckboxHidden = false;

        //uiConfig.privacyOffsetX = isiOS ? (20 + uiConfig.privacyCheckboxSize) : null;
        uiConfig.privacyOffsetY = 30; // 距离底部距离
        uiConfig.privacyVerticalLayoutItem = JVIOSLayoutItem.ItemSuper;
        // uiConfig.clauseName = "协议1";
        // uiConfig.clauseUrl = "http://www.baidu.com";
        // uiConfig.clauseBaseColor = Colors.black.value;
        // uiConfig.clauseNameTwo = "协议二";
        // uiConfig.clauseUrlTwo = "http://www.hao123.com";
        // uiConfig.clauseColor = Colors.red.value;
        // uiConfig.privacyText = ["1极", "2光", "3认", "4证"];
        // uiConfig.privacyTextSize = 13;
        //uiConfig.privacyWithBookTitleMark = true;
        //uiConfig.privacyTextCenterGravity = false;
        uiConfig.authStatusBarStyle = JVIOSBarStyle.StatusBarStyleDarkContent;
        uiConfig.privacyStatusBarStyle = JVIOSBarStyle.StatusBarStyleDefault;
        uiConfig.modelTransitionStyle =
            JVIOSUIModalTransitionStyle.CrossDissolve;

        uiConfig.statusBarColorWithNav = true;
        uiConfig.virtualButtonTransparent = true;

        uiConfig.privacyStatusBarColorWithNav = true;
        uiConfig.privacyVirtualButtonTransparent = true;

        uiConfig.needStartAnim = true;
        uiConfig.needCloseAnim = true;
        uiConfig.enterAnim = "activity_slide_enter_bottom";
        uiConfig.exitAnim = "activity_slide_exit_bottom";

        uiConfig.privacyNavColor = Colors.red.value;
        uiConfig.privacyNavTitleTextColor = Colors.blue.value;
        uiConfig.privacyNavTitleTextSize = 16;

        uiConfig.privacyNavTitleTitle = "ios lai le"; //only ios
        uiConfig.privacyNavTitleTitle1 = "协议11 web页标题";
        uiConfig.privacyNavTitleTitle2 = "协议22 web页标题";
        uiConfig.privacyNavReturnBtnImage = "return_bg"; //图片必须存在;

        //弹框模式
        // JVPopViewConfig popViewConfig = JVPopViewConfig();
        // popViewConfig.width = (screenWidth - 100.0).toInt();
        // popViewConfig.height = (screenHeight - 150.0).toInt();
        //
        // uiConfig.popViewConfig = popViewConfig;

        /// 添加自定义的 控件 到授权界面
        List<JVCustomWidget> widgetList = [];

        /// 步骤 1：调用接口设置 UI
        jverify.setCustomAuthorizationView(true, uiConfig,
            landscapeConfig: uiConfig, widgets: widgetList);

        /// 步骤 2：调用一键登录接口

        /// 方式一：使用同步接口 （如果想使用异步接口，则忽略此步骤，看方式二）
        /// 先，添加 loginAuthSyncApi 接口回调的监听
        jverify.addLoginAuthCallBackListener((event) {
          setState(() {
            _hideLoading();
            _hideLoading();
            _result = "监听获取返回数据：[${event.code}] message = ${event.message}";
          });
          print(
              "通过添加监听，获取到 loginAuthSyncApi 接口返回数据，code=${event.code},message = ${event.message},operator = ${event.operator}");
          requestDataWithToken(event.message);
        });

        /// 再，执行同步的一键登录接口
        jverify.loginAuthSyncApi(autoDismiss: true);
      } else {
        setState(() {
          _hideLoading();
          _result = "[2016],msg = 当前网络环境不支持认证";
        });

        /*
        final String text_widgetId = "jv_add_custom_text";// 标识控件 id
        JVCustomWidget textWidget = JVCustomWidget(text_widgetId, JVCustomWidgetType.textView);
        textWidget.title = "新加 text view 控件";
        textWidget.left = 20;
        textWidget.top = 360 ;
        textWidget.width = 200;
        textWidget.height  = 40;
        textWidget.backgroundColor = Colors.yellow.value;
        textWidget.isShowUnderline = true;
        textWidget.textAlignment = JVTextAlignmentType.center;
        textWidget.isClickEnable = true;

        // 添加点击事件监听
        jverify.addClikWidgetEventListener(text_widgetId, (eventId) {
          print("receive listener - click widget event :$eventId");
          if (text_widgetId == eventId) {
            print("receive listener - 点击【新加 text】");
          }
        });
        widgetList.add(textWidget);

        final String btn_widgetId = "jv_add_custom_button";// 标识控件 id
        JVCustomWidget buttonWidget = JVCustomWidget(btn_widgetId, JVCustomWidgetType.button);
        buttonWidget.title = "新加 button 控件";
        buttonWidget.left = 100;
        buttonWidget.top = 400;
        buttonWidget.width = 150;
        buttonWidget.height  = 40;
        buttonWidget.isShowUnderline = true;
        buttonWidget.backgroundColor = Colors.brown.value;
        //buttonWidget.btnNormalImageName = "";
        //buttonWidget.btnPressedImageName = "";
        //buttonWidget.textAlignment = JVTextAlignmentType.left;

        // 添加点击事件监听
        jverify.addClikWidgetEventListener(btn_widgetId, (eventId) {
          print("receive listener - click widget event :$eventId");
          if (btn_widgetId == eventId) {
            print("receive listener - 点击【新加 button】");
          }
        });
        widgetList.add(buttonWidget);
        */

        /* 弹框模式
        JVPopViewConfig popViewConfig = JVPopViewConfig();
        popViewConfig.width = (screenWidth - 100.0).toInt();
        popViewConfig.height = (screenHeight - 150.0).toInt();

        uiConfig.popViewConfig = popViewConfig;
        */

        /*

        /// 方式二：使用异步接口 （如果想使用异步接口，则忽略此步骤，看方式二）

        /// 先，执行异步的一键登录接口
        jverify.loginAuth(true).then((map) {

          /// 再，在回调里获取 loginAuth 接口异步返回数据（如果是通过添加 JVLoginAuthCallBackListener 监听来获取返回数据，则忽略此步骤）
          int code = map[f_code_key];
          String content = map[f_msg_key];
          String operator = map[f_opr_key];
          setState(() {
           _hideLoading();
            _result = "接口异步返回数据：[$code] message = $content";
          });
          print("通过接口异步返回，获取到 loginAuth 接口返回数据，code=$code,message = $content,operator = $operator");
        });

        */

      }
    });
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    // 初始化 SDK 之前添加监听
    jverify.addSDKSetupCallBackListener((JVSDKSetupEvent event) {
      print("receive sdk setup call back event :${event.toMap()}");
    });

    jverify.setDebugMode(true); // 打开调试模式
    jverify.setup(
        appKey: "d9d3e82fcd8e8e61b115da35", //"你自己应用的 AppKey",
        channel: "devloper-default"); // 初始化sdk,  appKey 和 channel 只对ios设置有效
    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    /// 授权页面点击时间监听
    jverify.addAuthPageEventListener((JVAuthPageEvent event) {
      print("receive auth page event :${event.toMap()}");
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
          child: Stack(
        children: [
          Image.asset(
            'images/login_bg.png',
            fit: BoxFit.fill,
            height: Get.height,
          ),
          Container(
            color: Colors.black54,
          ),
          Align(
            alignment: const Alignment(0, -0.7),
            child: Image.asset(
              'images/log_icon.png',
              width: 80,
              height: 80,
            ),
          ),
          GestureDetector(
            onTap: () {
              loginAuth();
            },
            child: Align(
              child: Container(
                width: Get.width - 30,
                height: 44,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(25),
                  gradient: LinearGradient(colors: [
                    // Color(0xffde53fc),
                    HexColor('#5C97FF'),
                    HexColor('#2C3CE2'),
                    // Color(0xff846dfc),
                    // Color(0xff30c1fd),
                  ]),
                ),
                child: const Text(
                  '本机号码一键登录',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
          ),
          GestureDetector(
            onTap: () {
              Get.to(LoginView());
            },
            child: Align(
              alignment: const Alignment(0, 0.15),
              child: Container(
                width: Get.width - 30,
                height: 44,
                alignment: Alignment.center,
                child: const Text(
                  '使用验证码或密码登录',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
          ),
          GestureDetector(
            onTap: () {
              Get.to(LoginFace());
            },
            child: Align(
              alignment: const Alignment(0, 0.25),
              child: Container(
                width: Get.width - 30,
                height: 44,
                alignment: Alignment.center,
                child: const Text(
                  '使用人脸识别登录',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
          )
        ],
      )),
    );
  }
}
